import { defineStore } from 'pinia'
import api from '@/api'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
    isAuthenticated: !!localStorage.getItem('token')
  }),
  actions: {
    async login(credentials) {
      const response = await api.auth.login(credentials)
      this.token = response.data.token
      this.user = {
        id: response.data.id,
        username: response.data.username,
        email: response.data.email,
        roles: response.data.roles
      }
      this.isAuthenticated = true
      localStorage.setItem('token', this.token)
      localStorage.setItem('refreshToken', response.data.refreshToken)
      return response
    },
    async logout() {
      try {
        await api.auth.logout()
        this.resetAuthState()
      } catch (error) {
        this.resetAuthState()
        throw error
      }
    },
    resetAuthState() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
    },
    async refreshToken() {
      try {
        const refreshToken = localStorage.getItem('refreshToken')
        const response = await api.auth.refreshToken(refreshToken)
        this.token = response.data.token
        localStorage.setItem('token', this.token)
        localStorage.setItem('refreshToken', response.data.refreshToken)
        return response
      } catch (error) {
        this.resetAuthState()
        throw error
      }
    },
    async checkAuth() {
      if (!this.token) return false
      
      try {
        // 直接使用当前存储的用户信息验证
        if (this.user && this.user.id) {
          return true
        }
        
        // 如果没有用户信息，尝试刷新token获取
        await this.refreshToken()
        this.isAuthenticated = true
        return true
      } catch (error) {
        this.resetAuthState()
        return false
      }
    }
  }
})
